package com.ruoyi.web.controller.common;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.lark.oapi.Client;
import com.lark.oapi.core.Config;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.approval.v4.model.*;
import com.lark.oapi.service.contact.v3.model.*;
import com.lark.oapi.service.contact.v3.model.User;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.ruoyi.baseMain.domain.bo.*;
import com.ruoyi.baseMain.domain.vo.BaseAccountVo;
import com.ruoyi.baseMain.domain.vo.BaseCustomVo;
import com.ruoyi.baseMain.domain.vo.BasePolicyHisVo;
import com.ruoyi.baseMain.service.IBaseCustomService;
import com.ruoyi.baseMain.service.IBasePolicyHisService;
import com.ruoyi.baseMain.service.IBasePolicyService;
import com.ruoyi.baseMain.service.impl.BaseAccountServiceImpl;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.ocean.domain.bo.OceanLogTotalBo;
import com.ruoyi.ocean.domain.vo.OceanLogTotalVo;
import com.ruoyi.ocean.mapper.OceanLogTotalMapper;
import com.ruoyi.system.domain.SysUserOnline;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.api.Department;
import com.ruoyi.GetToken;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author linziheng
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/wechat")
public class OpenController {


    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private final IBasePolicyService iBasePolicyService;
    @Autowired
    private final IBasePolicyHisService iBasePolicyHisService;
    @Autowired
    private final IBaseCustomService iBaseCustomService;
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private BaseAccountServiceImpl baseAccountServiceImpl;

    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private final OceanLogTotalMapper baseMapper;


    @GetMapping("/updateCusTaskStatus")
    public R updateCusTaskStatus() throws Exception {
        GetToken getToken = new GetToken();
        Client client = Client.newBuilder(getToken.appId, getToken.appSecret).build();
        List<BaseCustomBo> list = iBaseCustomService.queryListInstanceIdIsNotNull();
        for (BaseCustomBo baseCustomBo : list) {
            GetInstanceReq req = GetInstanceReq.newBuilder()
                .instanceId(baseCustomBo.getInstanceCode())
//            .locale("zh-CN")
//            .userId("f7cb567e")
//            .userIdType("user_id")
                .build(); GetInstanceResp resp = client.approval().v4().instance().get(req);
            if(baseCustomBo.getStatus().equals("1")&&!Objects.isNull(baseCustomBo.getSigns()) && baseCustomBo.getSigns().equals("审核中")){
                if (resp.getData().getStatus().equals("APPROVED")) {
                    //通过
                    baseCustomBo.setSigns("已签署");

                }else if(resp.getData().getStatus().equals("REJECTED")){
                    //拒绝
                    baseCustomBo.setSigns("未签署");
                }
            }else{
                if (resp.getData().getStatus().equals("APPROVED")) {
                    //通过
                    baseCustomBo.setStatus("1");
                }else if(resp.getData().getStatus().equals("REJECTED")){
                    //拒绝
                    baseCustomBo.setStatus("0");
                }


            }

            iBaseCustomService.updateByBo(baseCustomBo);
        }
        return R.ok();
    }

    @GetMapping("/getTaskStatus")
    public R getTaskStatus() throws Exception {
        GetToken getToken = new GetToken();
        Client client = Client.newBuilder(getToken.appId, getToken.appSecret).build();

        List<BasePolicyBo> list = iBasePolicyService.queryListInstanceIdIsNotNull();
        for (BasePolicyBo basePolicyBo : list) {
            // 创建请求对象
            GetInstanceReq req = GetInstanceReq.newBuilder()
                .instanceId(basePolicyBo.getInstanceCode())
//            .locale("zh-CN")
//            .userId("f7cb567e")
//            .userIdType("user_id")
                .build();

            // 发起请求
            GetInstanceResp resp = client.approval().v4().instance().get(req);

            if(resp.getCode()!=1390003){
                if(resp.getData().getStatus().equals("APPROVED")){
                    // 审批通过
                    BasePolicyHisBo basePolicyHisBo = new BasePolicyHisBo();
                    basePolicyHisBo.setInstanceCode(resp.getData().getInstanceCode());

                    List<BasePolicyHisVo> basePolicyHisVos = iBasePolicyHisService.queryList(basePolicyHisBo);
                    if(basePolicyHisVos.size()==1){
                        if(basePolicyHisVos.get(0).getStatus().equals("2") || basePolicyHisVos.get(0).getStatus().equals("4")){
                            //先判断是否到达生效日期
                            String status;
                            if(System.currentTimeMillis()<basePolicyBo.getTakeTime().getTime()){
                                status="4";
                            }else{
                                status="1";
                                //需要反写 返点 和销售人员
    //                            SysUser sysUser = iSysUserService.selectUserByRemark(resp.getData().getOpenId());
                                BaseAccountBo bo = new BaseAccountBo();
                                //现在是查询客户一样合作媒体一样政策一样的开户信息
                                bo.setCustomName(basePolicyBo.getNickName());
                                bo.setSignatory(basePolicyBo.getSignatory());
                                bo.setBidding(basePolicyBo.getPolicyType());
                                List<BaseAccountVo> baseAccountVos = baseAccountServiceImpl.queryList(bo);
                                List<BaseAccountBo> baseAccountBos = BeanUtil.copyToList(baseAccountVos, BaseAccountBo.class);
                                for (BaseAccountBo baseAccountBo : baseAccountBos) {
                                    baseAccountBo.setPoint(basePolicyBo.getTotalPoint());
                                    baseAccountBo.setSaleUserName(basePolicyBo.getOperateUserName());
    //                                baseAccountServiceImpl.updateByBo(baseAccountBo);
                                }
                            }
                            BasePolicyBo basePBo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyBo.class);
                            BasePolicyHisBo hbo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyHisBo.class);
                            basePBo.setId(basePolicyHisVos.get(0).getPolicyId());
                            basePBo.setStatus(status);
    //                        iBasePolicyService.updateByBo(basePBo);
                            hbo.setStatus(status);
                            SysUser user = iSysUserService.selectUserByRemark(resp.getData().getOpenId());
                            String username = "";
                            String userId = "";
                            if(!Objects.isNull(user)){
                                username = user.getNickName();
                                userId = user.getUserId().toString();
                            }else{
                                username = resp.getData().getOpenId();
                                userId = resp.getData().getOpenId();
                            }
                            hbo.setApproveUser(userId);
                            hbo.setApproveUserName(username);
    //                       iBasePolicyHisService.updateByBo(hbo);
                        }
                    }
                }else if(resp.getData().getStatus().equals("REJECTED")){
                    // 审批拒绝
                    BasePolicyHisBo basePolicyHisBo = new BasePolicyHisBo();
                    basePolicyHisBo.setInstanceCode(resp.getData().getInstanceCode());


                    List<BasePolicyHisVo> basePolicyHisVos = iBasePolicyHisService.queryList(basePolicyHisBo);
                    if(list.size()==1){
                        if(list.get(0).getStatus().equals("2")){
                            //更新数据
                            BasePolicyBo baseBo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyBo.class);
                            BasePolicyHisBo hbo = BeanUtil.toBean(basePolicyHisVos.get(0), BasePolicyHisBo.class);
                            baseBo.setId(basePolicyHisVos.get(0).getPolicyId());
                            baseBo.setStatus("3");
    //                       iBasePolicyService.updateByBo(baseBo);
                            hbo.setStatus("3");
                            SysUser user = iSysUserService.selectUserByRemark(resp.getData().getOpenId());
                            String username = "";
                            String userId = "";
                            if(!Objects.isNull(user)){
                                username = user.getNickName();
                                userId = user.getUserId().toString();
                            }else{
                                username = resp.getData().getOpenId();
                                userId = resp.getData().getOpenId();
                            }
                            hbo.setApproveUser(userId);
                            hbo.setApproveUserName(username);
    //                       iBasePolicyHisService.updateByBo(hbo);
                        }
                    }
                }
            }
            // 业务数据处理  APPROVED  通过  PENDING  审批中  REJECTED 拒绝
            System.out.println(Jsons.DEFAULT.toJson(resp.getData()));

        }
        return R.ok();
    }
    @GetMapping("/findByDepartment")
    public R findByDepartment() throws Exception {
        // 构建client
        GetToken getToken = new GetToken();
        Client client = Client.newBuilder(getToken.appId, getToken.appSecret).build();
        List<SysDept> depts = iSysDeptService.findByDepartment();
        for (SysDept dept : depts) {
            if(dept.getDeptId()!=100L){
                // 创建请求对象
                FindByDepartmentUserReq req = FindByDepartmentUserReq.newBuilder()
                    .departmentId(dept.getDepartmentId())
                    .build();

                // 发起请求
                FindByDepartmentUserResp resp = client.contact().v3().user().findByDepartment(req);
                for (User item : resp.getData().getItems()) {
                    SysUser user = new SysUser();
                    user.setDeptId(dept.getDeptId());
                    user.setRemark(item.getOpenId());
                    user.setLeaderUserId(item.getLeaderUserId());
                    user.setNickName(item.getName());
                    user.setUserName(item.getMobile().replace("+86",""));
                    user.setUserType("sys_user");
                    SysUser temp = iSysUserService.selectUserByRemark(item.getOpenId());
                    if(Objects.isNull(temp)){
                        user.setPassword("$2a$10$L/MJa99w0byDT/b4mnv67uVURzYDSCmk54NkcZmUkmZU/idD8H9by");//123456
                        iSysUserService.insertUser(user);
                    }else{
                     //   user.setUserId(temp.getUserId());
                        iSysUserService.updateUser(user);
                    }

                }

                // 处理服务端错误
                if (!resp.success()) {
                    System.out.println(String.format("code:%s,msg:%s,reqId:%s"
                        , resp.getCode(), resp.getMsg(), resp.getRequestId()));
                }
            }

        }


        return R.ok();
    }
    @GetMapping("/getOpenDept")
    public R getOpenDept() throws Exception {
        GetToken getToken = new GetToken();
        String tenantAccessToken = getToken.getTenantAccessTokenBySelfBuiltApp();
        Config config = new Config();
        config.setAppId(getToken.appId);
        config.setAppSecret(getToken.appSecret);
        Department Department = new Department(config);
        ChildrenDepartmentReq req = new ChildrenDepartmentReq();
        req.setDepartmentId("0");
        ChildrenDepartmentResp childrenDepartmentResp = Department.children(req);
        for (com.lark.oapi.service.contact.v3.model.Department item : childrenDepartmentResp.getData().getItems()) {
            SysDept sysDept = new SysDept();
            sysDept.setDepartmentId(item.getOpenDepartmentId());
            sysDept.setDeptName(item.getName());
            sysDept.setParentId(100L);
            sysDept.setOrderNum(Integer.valueOf(item.getOrder()));
            sysDept.setLeader(item.getLeaderUserId());
            sysDept.setAncestors("0,100");
            iSysDeptService.insertDept(sysDept);
        }
        return R.ok(childrenDepartmentResp.getData().getItems());
    }


    @GetMapping("/findByDepartmentUserSample")
    public R findByDepartmentUserSample() throws Exception {
        GetToken getToken = new GetToken();
        String tenantAccessToken = getToken.getTenantAccessTokenBySelfBuiltApp();
        Config config = new Config();
        config.setAppId(getToken.appId);
        config.setAppSecret(getToken.appSecret);
        Department Department = new Department(config);
        ChildrenDepartmentReq req = new ChildrenDepartmentReq();
        req.setDepartmentId("0");
        ChildrenDepartmentResp childrenDepartmentResp = Department.children(req);
        return R.ok(childrenDepartmentResp.getData().getItems());
    }

    @GetMapping("/getToken")
    public R getToken() throws Exception {
        GetToken getToken = new GetToken();
        return R.ok(getToken.getTenantAccessTokenBySelfBuiltApp());
    }
    /**
     * 回调
     */
    @GetMapping("/addMongo")
    public R addMongo() {
        mongoTemplate.dropCollection(OceanLogTotalVo.class);
        List<OceanLogTotalVo> list = baseMapper.selectTotalNoPage();

        List<OceanLogTotalVo> list2 = baseMapper.selectTotal(new OceanLogTotalBo());
        List<OceanLogTotalVo> org = list;
        org.forEach(item -> {
            for (OceanLogTotalVo item1 : list2) {
                if(item.getAccountId().equals(item1.getAccountId()) && item.getMonth().equals(item1.getMonth())){
                    item.setDTotal(item1.getDTotal());
                    item.setQTotal(item.getTotal() - item1.getDTotal());

                }
            }
        });
        long ids = System.currentTimeMillis();
        for (OceanLogTotalVo item : org) {
            ids++;
            if(item.getDTotal()==null){
                item.setDTotal(0L);
                item.setQTotal(item.getTotal() - item.getDTotal());
            }
            item.setId(ids);
        }




        mongoTemplate.insertAll(org);

        return R.ok();
    }
    @GetMapping("/dropCollection")
    public R dropCollection() throws IOException {
        //shanchu
        mongoTemplate.dropCollection(OceanLogTotalVo.class);
        return R.ok();
    }

    @GetMapping("/select")
    public PageImpl<OceanLogTotalVo> select() throws IOException {
        int page = 1;
        int size = 10;
        int skip = (page - 1) * size;
        DBObject obj = new BasicDBObject();
        //查询条件
//        obj.put("id", new BasicDBObject("$eq", "100121"));
//
        BasicDBObject fieldsObject = new BasicDBObject();
        //展示列
        fieldsObject.put("id", 1);
        fieldsObject.put("accountId", 1);
        fieldsObject.put("total", 1);
        fieldsObject.put("dTotal", 1);
        fieldsObject.put("qTotal", 1);
        fieldsObject.put("isOk", 1);
        fieldsObject.put("month", 1);
        fieldsObject.put("createTime", 1);
        // 创建查询对象
        BasicQuery query = new BasicQuery(obj.toString(), fieldsObject.toString()); // 这里使用空JSON对象查询所有文档
        query.skip(skip); // 设置跳过的文档数
        query.limit(size); // 设置返回的文档数上限

        // 执行查询
        List<OceanLogTotalVo> content = mongoTemplate.find(query, OceanLogTotalVo.class);

        // 获取总文档数（可以进一步优化为只查询一次）
        long total = mongoTemplate.count(new BasicQuery("{}"), OceanLogTotalVo.class);

        // 创建分页对象
        PageRequest pageRequest = PageRequest.of(page, size);
        return new PageImpl<>(content, pageRequest, total);
    }
}
